<template>
  <div class="container">
    <div class="left">
      <div class="title">重开采购单</div>
      <div class="leftContext">
        <div class="codeInfo">
          <div>
            采购编号：<span style="color: #436ae8">{{ table.oddNumber }}</span>
          </div>
          <div>制单人：{{ table.createdByName }}</div>
          <div>制单时间：{{ $moment(table.createdTime) }}</div>
        </div>
        <el-table :data="table.goodsList">
          <el-table-column
            label="操作"
            type="index"
            width="80"
          >
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="delBut(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="序号"
            type="index"
            width="55"
            @row-click=""
          ></el-table-column>
          <el-table-column label="图片">
            <template slot-scope="scope">
              <img
                v-if="scope.row.image"
                @click="openDetails(scope.row)"
                style="width: 50px; height: 50px"
                :src="ImgHttps + scope.row.image.split(',')[0]"
                alt=""
              />
              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="编号">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)" v-if="scope.row.code">{{
                scope.row.code
              }}</span>
              <span @click="openDetails(scope.row)" v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" show-overflow-tooltip min-width="120px;">
            <template slot-scope="scope">
              <span @click="(scope.row)">{{ scope.row.title }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品类型">
            <template slot-scope="scope">
              <span
                @click="openDetails(scope.row)"
                v-if="scope.row.goodsType == 1"
                >商品</span
              >
              <span @click="openDetails(scope.row)" v-else>赠品</span>
            </template>
          </el-table-column>
          <el-table-column label="品牌">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.brandName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分类">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.typeName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.sellPrice
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.specificationName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际库存">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.quantityStock
              }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="right">
      <div class="title">操作</div>
      <div class="rightContext" style="border: 0">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="采购部门">
            <div class="selectTree">
              <treeselect
                :options="options"
                v-model="form.bumenCode"
                search-nested
                :normalizer="normalizer"
                noResultsText="未找到"
                placeholder="请选择"
              >
              </treeselect>
            </div>
          </el-form-item>
          <el-form-item label="供应商">
            <el-input
              size="small"
              placeholder="请输入供应商名称"
              :value="form.supplierName"
              supplierName
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="采购类型">
            <el-input
              size="small"
              placeholder="请输入采购类型"
              :value="form.goodsType == 1 ? '商品' : '赠品'"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="采购商品">
            <el-input
              size="small"
              placeholder="请输入采购商品"
              :value="form.title"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="采购规格">
            <el-input
              size="small"
              placeholder="请输入采购规格"
              :value="form.specificationName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="采购品牌">
            <el-input
              size="small"
              placeholder="请输入采购品牌"
              :value="form.brandName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="采购金额">
            <el-input
              size="small"
              placeholder="请输入采购金额"
              :value="form.sellPrice * form.numberTotal"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="采购数量">
            <el-input
              size="small"
              placeholder="请输入采购数量"
              disabled
              :value="form.numberTotal"
            ></el-input>
          </el-form-item>
          <el-form-item label="入库仓库">
            <div
              v-for="(ite, index) in form.selectObj"
              :key="index"
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <el-select
                :value="ite.warName"
                size="mini"
                value-key="id"
                placeholder="请选择"
                :disabled="ite.goodsType == 0"
                @change="myWareListChange($event, ite)"
              >
                <el-option
                  v-for="item in wareList.list"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
              <div style="display: flex; align-items: center">
                <el-input-number
                  size="mini"
                  :min="0"
                  style="margin-right: 10px"
                  placeholder="请输入库存数量"
                  v-model="ite.number"
                  @change="inputChange(ite)"
                ></el-input-number>

                <i
                  class="el-icon-remove-outline"
                  style="cursor: pointer"
                  @click="deleteMyWare(ite, ite.goodsType != undefined ? 1 : 0)"
                ></i>
              </div>
            </div>
            <i
              class="el-icon-circle-plus-outline"
              style="cursor: pointer"
              @click="addMyWareList()"
            ></i>
          </el-form-item>
          <el-form-item label="上传图片">
            <el-upload
              class="video"
              ref="upload"
              action="#"
              multiple
              :before-upload="beforeUploadImg"
              :http-request="imgUpload"
              :show-file-list="false"
            >
              <el-button type="primary" size="mini">选择图片</el-button>
            </el-upload>
            <div
              v-if="form.fileListImg"
              class="liimg"
              v-for="(itemsImg, index) in form.fileListImg"
              :key="index"
            >
              <img
                v-if="itemsImg"
                :src="ImgHttps + itemsImg.img"
                class="img-avatar"
                v-image-preview
              />
              <p v-if="itemsImg" class="close" @click="delectImgList(index)">
                <i class="el-icon-error"></i>
              </p>
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input maxlength="255" placeholder="请输入备注" type="textarea" v-model="textarea"></el-input>
          </el-form-item>
        </el-form>
        <p style="text-align: right; margin-top: 50px">
          <el-button type="primary" size="mini" @click="submit"
            >确认</el-button
          >
          <el-button size="mini" @click="cancel"
            >取消</el-button
          >
        </p>
      </div>
    </div>
  </div>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  data() {
    return {
      table: {
        list: [],
      },
      form: {}, //表单数据
      wareList: {
        list: [],
      },
      normalizer(node) {
        return {
          id: node.orgCode,
          label: node.orgName,
          children: node.children,
        };
      },
      options: [],
      textarea:""
    };
  },
  created() {
    this.getWareList();
    this.getDetail(this.$route.query.id);
    this.department();
  },
  activated() {
    // this.getWareList();
    this.getDetail(this.$route.query.id);
    // this.department();
  },
  methods: {
    delBut(i){
      this.table.goodsList.splice(i,1);
    },
    cancel(){
      this.$store.commit("clearToolItem", "/purchasingReopen");
      this.$router.go(-1);
    },
    openDetails(row) {
      this.form = row;
    },
    // 数据提交
    submit: _.debounce(function () {
      // 数据处理
      let itemList = [];
      for (let i in this.table.goodsList) {
        if (
          this.table.goodsList[i].bumenCode == "" ||
          this.table.goodsList[i].bumenCode == null
        ) {
          this.$message.warning("请选择采购的部门");
          return false;
        } else if (
          this.table.goodsList[i].selectObj[0] && this.table.goodsList[i].selectObj[0].warId == "" &&
          this.table.goodsList[i].selectObj[0].number == 0
        ) {
          this.$message.warning("请选择采购入库的仓库与数量");
          return false;
        } else if (this.table.goodsList[i].fileListImg == "") {
          this.$message.warning("请选择上传的图片");
          return false;
        }
        this.table.goodsList[i].purchaseProdImage = ""; //初始化值

        for (let j in this.table.goodsList[i].fileListImg) {
          this.table.goodsList[i].purchaseProdImage +=
            this.table.goodsList[i].fileListImg[j].img + ",";
        }

        this.getMenuBtnList(
          this.options,
          this.table.goodsList[i].bumen,
          this.table.goodsList[i].bumenCode
        );

        itemList.push({
          purchaseOrgCode: this.table.goodsList[i].bumenCode,
          purchaseOrgName:
            this.table.goodsList[i].bumen.length != 0
              ? this.table.goodsList[i].bumen[0].lable
              : "",
          purchaseProdAmount:
            this.table.goodsList[i].sellPrice *
            this.table.goodsList[i].numberTotal,
          purchaseProdId: this.table.goodsList[i].id,
          purchaseProdImage: this.table.goodsList[i].image,
          purchaseImage:this.table.goodsList[i].purchaseProdImage,
          purchaseProdQuantity: this.table.goodsList[i].numberTotal,
          purchaseProdType: this.table.goodsList[i].goodsType,
          supplierId: this.table.goodsList[i].supplierId,
          warehouses: this.table.goodsList[i].selectObj,
        });
        for(let g in this.table.goodsList[i].selectObj){
          if((this.table.goodsList[i].selectObj[g].warName == "" || this.table.goodsList[i].selectObj[g].warId == "") || this.table.goodsList[i].selectObj[g].number == 0){
            this.$message.warning("仓库名，仓库数量都不能为空哦");
            return false;
          }
        }
      }

      

      this.axios
        .post("/order/v1/purchase/order/reopenPurchaseOrder", {
          purchaseOrderNo: this.table.oddNumber,
          oldPurchaseOrderNo:this.$route.query.id,
          itemList: itemList,
          comment:this.textarea
        })
        .then((res) => {
          console.log(res);
          if (res.code == 0) {
            this.$message.success("提交成功!");
            this.$store.commit("clearToolItem", "/purchasingReopen");
            this.$router.go(-1);
          } else {
            this.$message.error(res.message);
          }
        });
    }, 300),

    // 递归
    getMenuBtnList(menuTreeList, menuList, code) {
      for (let item of menuTreeList) {
        if (item.orgCode == code) {
          menuList.push({
            lable: item.orgName,
            orgCode: item.orgCode,
            goodsType: item.goodsType,
          });
        } else if (item.children && item.children.length > 0) {
          this.getMenuBtnList(item.children, menuList, code);
        }
      }
    },
    inputChange(e) {
      this.$forceUpdate();
      this.numberTotalWare();
    },
    // 计算采购总库存
    numberTotalWare() {
      let numberTotal = 0;
      for (let i in this.form.selectObj) {
        numberTotal += this.form.selectObj[i].number;
      }
      this.form.numberTotal = numberTotal;
    },
    // 部门选择列表
    department() {
      this.axios
        .post(
          "/sys/v1/org/tree/select",
          {
            request: {
              orgName: "",
              orgType: "",
            },
            version: "",
          },
          {
            headers: {
              isLoading: false,
            },
          }
        )
        .then((res) => {
          if (res.code == 0) {
            this.options = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    getDetail(e) {
      this.axios
        .get(
          "order/v1/purchase/order/purchaseOrderDetails?purchaseOrderNo=" + e
        )
        .then((res) => {
          this.axios
            .post("order/v1/purchase/order/fillInAllotNumber", {
              supplierIds: res.data.itemVOs.map((i) => i.supplierId),
              type: "CG",
            })
            .then((r) => {
              this.table = r.data;
              this.table.goodsList.forEach((item) => {
                this.$set(item,"numberTotal",0);
                this.$set(item,"selectObj",[]);
                this.$set(item,"fileListImg",[]);
                this.$set(item,"bumen",[]);
              });
              this.form = this.table.goodsList[0];
            });
        });
    },
    delectImgList(index) {
      this.form.fileListImg.splice(index, 1);
      this.$forceUpdate();
    },
    addMyWareList() {
      if (this.form.selectObj.length < this.wareList.list.length) {
        this.form.selectObj.push({
          comId: this.form.id,
          number: 0,
          warId: "",
          warName: "",
        });
        this.$forceUpdate();
      } else {
        this.$message.warning("不能再加了仓库只有这些");
      }
    },
    beforeUploadImg(file) {
      return new Promise((resolve, reject) => {
        let _URL = window.URL || window.webkitURL;
        let isLt2M = file.size / 1024 / 1024 > 4; // 判定图片大小是否小于4MB
        // 这里需要计算出图片的长宽
        let img = new Image();
        img.onload = function () {
          file.width = img.width; // 获取到width放在了file属性上
          file.height = img.height; // 获取到height放在了file属性上
          let valid = img.width > 2000; // 图片宽度大于2000
          // console.log(11, file)
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (valid || isLt2M) {
            imageConversion
              .compressAccurately(file, {
                size: 400,
                width: 2000,
              })
              .then((res) => {
                // console.log(33, res)
                resolve(res);
              });
          } else resolve(file);
        }; // 需要把图片赋值
        img.src = _URL.createObjectURL(file);
      });
    },
    imgUpload(fileObj) {
      let length = this.form.fileListImg.length;
      let formData = new FormData();
      formData.append("file", fileObj.file);

      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      if (length <= 5) {
        this.axios
          .post(
            "/sys/v1/common/upload/files?pathName=internalSystem",
            formData,
            config,
            {
              headers: {
                isLoading: false,
              },
            }
          )
          .then((res) => {
            console.log(res);
            if (res.code == 0) {
              // this.imageUrl = res.data.url;
              let obj = {
                img: res.data.url,
                creattime: new Date().toLocaleDateString(),
              };
              this.form.fileListImg.push(obj);
              this.$forceUpdate();
            } else {
              this.$message.error(res.message);
            }
          });
      } else {
        this.$message.warning("图片条数不能超过10条");
      }
    },
    //删除现在的仓库
    deleteMyWare(e, t) {
     if (t) {
        let temp = this.form.selectObj.find((res) => res.warId === e.warId);
        temp.type = 1;
      } else {
        this.form.selectObj.splice(
          this.form.selectObj.findIndex((res) => res.warId == e.warId),
          1
        );
      }
      this.numberTotalWare();
    },
    //自己选择的仓库修改了
    myWareListChange(e1, e2) {
        let temp = this.form.selectObj.find((res) => e1.id == res.warId);
      if (temp) {
        if (temp.type) {
          this.$message.warning("该仓库已删除不能选");
        } else {
          this.$message.warning("该仓库已存在");
        }
        return;
      }
      e2.warId = e1.id + "";
      e2.warName = e1.name;
      this.$forceUpdate();
    },
    getWareList() {
      this.axios.post("order/comm/commWarehouse/list",{
        pageSize:999,
        pageNo:1
      }).then((res) => {
        //仓库数据接口
        this.wareList = res.data;
        this.wareList.list = this.wareList.list.reverse();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  display: flex;
  height: 100%;
  .codeInfo {
    display: flex;
    justify-content: space-around;
    margin-top: 10px;
    div {
      font-size: 15px;
      color: #666;
    }
  }
  .left {
    overflow: auto;
    background: #fff;
    padding: 10px;
    flex: 1;
    min-width: 600px;
    .title {
      color: #6b6b6b;
      font-size: 16px;
      border-bottom: 2px solid #e3e7ec;
      padding-bottom: 10px;
    }
    .leftContext {
      margin-top: 10px;
      border: 1px solid#E3E7EC;
    }
  }
  .right {
    overflow: auto;
    flex: 1;
    background: #fff;
    padding: 10px;
    margin-left: 10px;
    min-width: 400px;
    .title {
      color: #6b6b6b;
      font-size: 16px;
      border-bottom: 2px solid #e3e7ec;
      padding-bottom: 10px;
    }
    .rightContext {
      margin-top: 10px;
      border: 1px solid#E3E7EC;
    }
  }
  .liimg {
  position: relative;
  display: inline-block;
  margin-right: 12px;
  width: 80px;

  p {
    text-align: center;
    font-size: 12px;
    color: #666;
  }

  .close {
    position: absolute;
    top: -20px;
    right: -10px;
    z-index: 10;
  }

  .close:hover {
    cursor: pointer;

    i {
      color: #006af1;
    }
  }

  .img-avatar {
    width: 80px;
    height: 80px;
    border-radius: 5px;
  }
}
  .selectTree {
    width: 100%;
    display: inline-block;
    vertical-align: middle;
    margin-right: 10px;
    height: 30px;

    /deep/.el-cascader .el-input .el-input__inner {
      line-height: 30px;
      height: 30px;
      width: 100%;
    }
    /deep/.el-cascader .el-input {
      width: 250px;
    }
  }
  /deep/.vue-treeselect {
    height: 30px;
  }
  /deep/.vue-treeselect--searchable .vue-treeselect__input-container {
    height: 30px;
    line-height: 30px;
  }
  /deep/.vue-treeselect__single-value {
    font-size: 14px;
    line-height: 30px;
  }
  /deep/.vue-treeselect__menu-container {
    font-size: 15px;
  }
  /deep/.vue-treeselect__multi-value-item {
    height: 20px;
    line-height: 20px;
    padding: 0;
  }
  /deep/.vue-treeselect__input {
    height: 28px;
    line-height: 28px;
    outline: none;
    border: none;
    padding: 0;
    // display: none;
    // border:1px solid #000;
  }
  /deep/.vue-treeselect__placeholder {
    font-size: 10px;
    line-height: 28px;
  }
  /deep/.vue-treeselect--has-value .vue-treeselect__multi-value {
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  /deep/.vue-treeselect__control {
    height: 30px;
  }
}
</style>